package com.loubii.account.ui.avtivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;

import com.loubii.account.R;
import com.loubii.account.app.AccountApplication;
import com.loubii.account.bean.UserBean;
import com.loubii.account.constants.UserList;
import com.loubii.account.db.DaoSession;
import com.loubii.account.db.UserBeanDao;

import java.util.List;

import butterknife.ButterKnife;
import butterknife.OnClick;

public class RegisterActivity extends Activity {

    final static String TestApp = "text_output";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        ButterKnife.bind(this);
    }

    @OnClick({R.id.register_btn})
    public void registerUser() {
        // 用户名
        EditText userText = (EditText)findViewById(R.id.re_user_val);
        String username = userText.getText().toString();
        // 密码
        EditText passText = (EditText)findViewById(R.id.re_pass_val);
        String password = passText.getText().toString();
        // 密码
        EditText repassText = (EditText)findViewById(R.id.re_repass_val);
        String repassword = repassText.getText().toString();
        // 用户名不能为空
        if(username.equals("")){
            Toast.makeText(this, "用户名不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        Log.d(TestApp, "username" + username);
        // 确认密码不一致
        if(!password.equals(repassword)){
            Toast.makeText(this, "确认密码不一致", Toast.LENGTH_SHORT).show();
            return;
        }
        // 注册数据
        if(userRegister(username, password)){
            Intent intent;
            intent = new Intent(this, MainTabActivity.class);
            startActivity(intent);
            Log.d(TestApp, "registerUser: success");
        }
    }

    public boolean userRegister(String username,String password){

        DaoSession dbDao = AccountApplication.getDaoSession();
        UserBean uE = new UserBean();
        uE.setName_id(username);
        uE.setPassword(password);
        try {
            // insert 一条记录，若存在相同用户名会报错 执行catch
            dbDao.insert(uE);
            Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT).show();
            return true;
        }catch (Exception e) {
            // 注册和登录公用 存在用户名为 修改密码情况
            dbDao.insertOrReplace(uE);
            Toast.makeText(this, "修改成功", Toast.LENGTH_SHORT).show();
            return true;
        }
    }
}

